import { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '../store/authStore';
import { type LoginParams } from '../types/auth';

export const useAuth = () => {
    const navigate = useNavigate();
    const {
        token,
        userInfo,
        authMenus,
        isLoading,
        login: storeLogin,
        logout: storeLogout,
        refreshAuth
    } = useAuthStore();

    // 新增：用于标记登录流程是否触发
    const [loginTriggered, setLoginTriggered] = useState(false);
    // 新增：存储登录成功后需要跳转的路径
    const [pendingRedirectPath, setPendingRedirectPath] = useState<string | null>(null);

    // 登录方法：仅负责触发登录，不直接跳转
    const login = useCallback(async (params: LoginParams, redirectPath = '/dashboard') => {
        try {
            setLoginTriggered(true); // 标记登录开始
            setPendingRedirectPath(redirectPath === '/' ? '/dashboard' : redirectPath);
            await storeLogin(params.username, params.password); // 等待登录和菜单加载完成
            return true;
        } catch (error) {
            setLoginTriggered(false); // 登录失败重置状态
            setPendingRedirectPath(null);
            return false;
        }
    }, [storeLogin]);

    // 监听：当登录触发且菜单加载完成后，执行跳转
    useEffect(() => {
        // 条件：登录已触发 + 菜单已加载（长度>0） + 有跳转路径
        if (loginTriggered && authMenus.length > 0 && pendingRedirectPath) {
            console.log('权限菜单加载完成，执行跳转:', pendingRedirectPath);
            navigate(pendingRedirectPath, { replace: true });
            // 跳转后重置状态
            setLoginTriggered(false);
            setPendingRedirectPath(null);
        }
    }, [authMenus, loginTriggered, pendingRedirectPath, navigate]);

    // 退出登录方法
    const logout = useCallback(() => {
        storeLogout();
        navigate('/login', { replace: true });
    }, [storeLogout, navigate]);

    return {
        token,
        userInfo,
        authMenus,
        isLoading,
        login,
        logout,
        refreshAuth
    };
};